package com.dyson.pool;

import lombok.Getter;
import lombok.Setter;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;

/**
 * @author:DysonWy@Gmail.com
 * @time:2019/8/10 13:36
 * 对connection的封装
 */
@Setter
@Getter
public class ConnectionPool implements InvocationHandler {
    //关闭连接方法名,源自Connection.close(),匹配此名称拦截
    private final static String CLOSE = "close";
    //真实连接
    private Connection realConnection;
    //代理连接
    private Connection proxyConnection;
    //指定数据源
    private DbPool dbPool;

    public ConnectionPool(Connection realConnection, DbPool dbPool) {
        this.realConnection = realConnection;
        this.dbPool = dbPool;
        //连接创建代理
        this.proxyConnection = (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(),
                new Class[]{Connection.class},
                this);
    }

    /**
     * 调用Connection对象方法时,执行此代理方法
     *
     * @param proxy
     * @param method
     * @param args
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //获取connection中当前调用方法名
        String methodName = method.getName();
        Object obj = null;
        if (methodName.equals(CLOSE)) {
            //拦截Connection.close(),连接归还给连接池
            dbPool.closeConnection(this);
        } else {
            //调用Connection其他方法
            obj = method.invoke(realConnection, args);
        }
        return obj;
    }
}
